﻿KISSY.use("validation, calendar, fgt/auth, fgt/ui", function (S, Validation, Calendar, Auth, UI) {
    S.ready(function (S) {
        var $ = S.all,
            J = jQuery,
            form = $("#J_Calendar"),
            VALID_EFFECT = "Simple",
            VALID_STYLE = "s_b",
            validator = new Validation(form[0], { warn: VALID_EFFECT, style: VALID_STYLE }),
            submitBtn = $("#J_Sumbit"),
            dateList = form.all(".date-list"),
            addADayBtn = $("#J_AddADay"),
            addDateIntervalBtn = $("#J_AddDateInterval"),
            dateSelectBtns = form.all(".start"),
            dateIntervalSelectBtns = form.all(".start-end"),
            radioBtn = $("#J_Calendar .type-radio"),
        //            rows = $("#J_Calendar .onetime"),
            popbox = UI.getPopbox();



        radioBtn.on("change", function (event) {
            event.halt();
            var self = $(this);
            if (self.val() == 0) {
                dateList.hide();
                addADayBtn.hide();
                addDateIntervalBtn.hide();

            }
            else if (self.val() == 1) {
                dateList.show();
                addADayBtn.show();
                addDateIntervalBtn.show();
            }
        });

        function submit() {
            Auth.validate(function () {
                try {
                    var paramStr = S.ajax.serialize(form),
                        resultCode = FGT.core.constant.jsonResultCode,
                        failureText = "Save failure, please try again later.",
                        delay = 1000;

                    J.ajax({
                        url: "/rv/save/calendar",
                        type: "POST",
                        data: paramStr,
                        beforeSend: function (jqXHR, settings) {
                            submitBtn.prop("disabled", true);
                            popbox.show("Saving");
                        },
                        success: function (data, textStatus, jqXHR) {
                            if (data.Result === resultCode.SUCCESS) {
                                popbox.show(data.Content, delay);
                            }
                            else {
                                var jsonData = data.Content;
                                if (S.isString(jsonData)) {
                                    popbox.show(jsonData, delay);
                                }
                                else if (S.isArray(jsonData)) {
                                    S.each(jsonData, function (item) {
                                        var target = $(item.id);
                                        if (target.attr("data-msgbox")) {
                                            var label = $(target.attr("data-msgbox"));
                                            if (label) {
                                                label.text(item.msg);
                                                label.removeClass("ok tip error");
                                                label.addClass("error");
                                                label.show();
                                            }
                                        }
                                    });
                                    popbox.hide();
                                }
                                submitBtn.prop("disabled", false);
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            submitBtn.prop("disabled", false);
                            popbox.show(failureText, delay);
                        }
                    });
                }
                catch (e) {
                    popbox.show(failureText, delay);
                    submitBtn.prop("disabled", false);
                }
            }, popbox, this);
        }

        submitBtn.on("click", function (event) {
            event.halt();
            submit();
        });

        function createCalendar(trigger) {
            var dateStorage = trigger.siblings(".start-storage"),
                selectedDate = new Date(dateStorage.val()),
                calendar;

            calendar = new Calendar(trigger, {
                date: selectedDate,
                selected: selectedDate,
                popup: true,
                closable: true,
                pages: 1,
                align: { points: ['bl', 'tl'], offset: [0, 0] }
            });

            calendar.on("select", function (event) {
                event.halt();
                var self = event.target,
                    trigger = self.trigger,
                    startStorage = trigger.siblings(".start-storage"),
                    endStorage = trigger.siblings(".end-storage"),
                    dateStr = S.Date.format(event.date, "isoDate");

                startStorage.val(dateStr);
                endStorage.val(dateStr);
                trigger.text(dateStr);
            });
        }

        function createRangeCalendar(trigger) {
            var startDateStorage = trigger.siblings(".start-storage"),
                endDateStorage = trigger.siblings(".end-storage"),
                startDate = new Date(startDateStorage.val()),
                endDate = new Date(endDateStorage.val()),
                calendar;

            calendar = new Calendar(trigger, {
                popup: true,
                rangeSelect: true,
                range: { start: new Date(startDate.getTime() - 86400000), end: new Date(endDate.getTime() - 86400000) },
                pages: 3,
                align: { points: ['bl', 'tl'], offset: [0, 0] }
            });

            calendar.on("rangeSelect", function (event) {
                event.halt();
                var self = event.target,
                    trigger = self.trigger,
                    startStorage = trigger.siblings(".start-storage"),
                    endStorage = trigger.siblings(".end-storage"),
                    startDateStr = S.Date.format(event.start, "isoDate"),
                    endDataStr = S.Date.format(event.end, "isoDate");

                startStorage.val(startDateStr);
                endStorage.val(endDataStr);
                trigger.text(startDateStr + " -> " + endDataStr);

                self.hide();
            });
        }

        addADayBtn.on("click", function (event) {
            event.halt();

            var index = S.guid(),
                startDateName = "dateIntervals[" + index + "].StartDate",
                endDateName = "dateIntervals[" + index + "].EndDate",
                startDate = new Date(),
                startDateStr = S.Date.format(startDate, "isoDate");
            id = "start_" + index;

            var html = "<li class='date-item'>"
                        + "<input type='hidden' name='dateIntervals.Index' value='" + index + "' />"
                        + "<a id='" + id + "' class='start btn btn1' href='javascript:;'>" + startDateStr + "</a>"
                        + "<input class='start-storage' type='hidden' name='" + startDateName + "' value='" + startDateStr + "'/>"
                        + "<input class='end-storage' type='hidden' name='" + endDateName + "' value='" + startDateStr + "'/>"
                        + "<a class='delete' href='javascript:;' onclick='func.deleteDate(this); return false;'>Delete</a>"
                     + "</li>";

            dateList.append(html);
            createCalendar($("#" + id));
        });

        addDateIntervalBtn.on("click", function (event) {
            event.halt();

            var index = S.guid(),
                startDateName = "dateIntervals[" + index + "].StartDate",
                endDateName = "dateIntervals[" + index + "].EndDate",
                startDate = new Date(),
                endDate = new Date(startDate.getTime() + 86400000),
                startDateStr = S.Date.format(startDate, "isoDate"),
                endDateStr = S.Date.format(endDate, "isoDate"),
                startEndDateStr = startDateStr + " -> " + endDateStr,
                id = "start_" + index;

            var html = "<li class='date-item'>"
                        + "<input type='hidden' name='dateIntervals.Index' value='" + index + "' />"
                        + "<a id='" + id + "' class='start-end btn btn1' href='javascript:;'>" + startEndDateStr + "</a>"
                        + "<input class='start-storage' type='hidden' name='" + startDateName + "' value='" + startDateStr + "'/>"
                        + "<input class='end-storage' type='hidden' name='" + endDateName + "' value='" + endDateStr + "'/>"
                        + "<a class='delete' href='javascript:;' onclick='func.deleteDate(this); return false;'>Delete</a>"
                     + "</li>";

            dateList.append(html);
            createRangeCalendar($("#" + id));
        });

        addDateIntervalBtn.on("click", function (event) {
            event.halt();
        });

        S.each(dateSelectBtns, function (item) {
            createCalendar($(item));
        });

        S.each(dateIntervalSelectBtns, function (item) {
            createRangeCalendar($(item));
        });

        S.mix(func, {
            deleteDate: function (target) {
                var $ = S.all,
                    self = $(target);

                self.parent(".date-item").remove();
            }
        });
    });
});